import { useEffect, useState } from 'react'

export default function useDebounce(value: any, delay = 300) {
	const [debouncedValue, setDebouncedValue] = useState(value)

	useEffect(() => {
		const handler = setTimeout(() => {
			setDebouncedValue(value)
		}, delay)

		// 下一次 value 和 delay 改变时,优先执行此函数
		return () => {
			clearTimeout(handler)
		}
	}, [value, delay])

	return debouncedValue
}
